package com.mmall.task;
import com.mmall.common.Const;
import com.mmall.common.RedissonManager;
import com.mmall.service.OrderService;
import com.mmall.util.PropertiesUtil;
import com.mmall.util.RedisPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class CloseOrderTask {

    @Autowired
    private OrderService orderService;
    @Autowired
    private RedissonManager redissonManager;

    //@Scheduled(cron = "0 */1 * * * ?")
    public void closeOrderTask(){
        log.info("关闭订单定时任务启动");
        int hour  = Integer.parseInt(PropertiesUtil.getProperty("close.order.task.time.hour","2"));
        orderService.closeOrder(hour);
        log.info("关闭订单定时结束执行");
    }

    //@Scheduled(cron = "0/3 * * * * ? ")
    public void testTask(){
        log.info("************每三秒执行*************");
    }

   // @Scheduled(cron = "0/3 * * * * ? ")
    public void closeTask(){
        log.info("task will soon start......");
        Long lockTimeout = Long.parseLong(PropertiesUtil.getProperty("lock.timeout","5000"));
        Long setnxResult = RedisPoolUtil.setnx(Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK,String.valueOf(System.currentTimeMillis()+lockTimeout));
        if(setnxResult!=null && setnxResult.intValue()==1){
            closeOrder(Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK);
        }else {
            log.info("oh,can't get lock:{}",Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK);
        }
    }

   // @Scheduled(cron = "0/3 * * * * ? ")
    public void closeTask2(){
        log.info("task will soon start......");
        Long lockTimeout = Long.parseLong(PropertiesUtil.getProperty("lock.timeout","5000"));
        Long setnxResult = RedisPoolUtil.setnx(Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK,String.valueOf(System.currentTimeMillis()+lockTimeout));
        if(setnxResult!=null && setnxResult.intValue()==1){
            closeOrder(Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK);
        }else {
              String lockValueStr  = RedisPoolUtil.get(Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK);
              if(lockValueStr!=null && System.currentTimeMillis()>Long.parseLong(lockValueStr)){
                  String ret = RedisPoolUtil.getSet(Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK,String.valueOf(System.currentTimeMillis()+lockTimeout));
                  if(ret==null||lockValueStr.equals(ret)){
                      closeOrder(Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK);
                  }else{
                      System.out.println("未能够获得分布式锁");
                  }

              }else {
                  System.out.println("未能够获取分布式锁");
              }
        }
    }

    /**
     *  通过Redisson进行加锁
     *
     * **/

    @Scheduled(cron = "0/3 * * * * ? ")
    public void closeTask3(){
        System.out.println("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
        RLock lock = redissonManager.getRedisson().getLock(Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK);
        boolean getLock = false;
        try {
            if(getLock=lock.tryLock(0,50, TimeUnit.SECONDS)){
               // System.out.println("Redisson获取到分布式锁，锁名:"+Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK+"当前线程："+Thread.currentThread().getName());
                log.info("Redisson获取到分布式锁:{},ThreadName:{}",Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK,Thread.currentThread().getName());
                Thread.sleep(3);
                System.out.println("*************************do something*************************");
            }else{
                //System.out.println("Sorry!Redisson没有获取到分布式锁，锁名:"+Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK+"当前线程："+Thread.currentThread().getName());
                log.info("Sorry!Redisson没有获取到分布式锁:{},ThreadName:{}",Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK,Thread.currentThread().getName());
            }
        } catch (InterruptedException e) {
           // System.out.println("获取分布式锁异常");
            log.info("获取分布式锁异常");
            e.printStackTrace();
        }finally {
            if(!getLock){
                return;
            }
            lock.unlock();
           // System.out.println("Redisson分布式锁释放锁");
            log.info("Redisson分布式锁释放锁");
        }


    }

    private void closeOrder(String lockName) {

        RedisPoolUtil.expire(lockName,50);
        log.info("get lock{}，ThreadName：{}",Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK,Thread.currentThread().getName());
        System.out.println("做点儿事");
        RedisPoolUtil.del(Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK);
        log.info("release lock{}，ThreadName：{}",Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK,Thread.currentThread().getName());
        log.info("=======================================");
    }
}
